#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os,json
import pexpect

def get_aqy_snmp_log():
    band_width_95_file_path = "/opt/soft/dcache/kcp/logs/snmp.log"
    try:
        if os.path.isfile(band_width_95_file_path):
            # Unix,BytesSent,BytesReceived,MaxConn,ActiveOpens,PassiveOpens,CurrEstab,InErrs,InCsumErrors,
            # KCPInErrors,InPkts,OutPkts,InSegs,OutSegs,InBytes,OutBytes,RetransSegs,FastRetransSegs,
            # EarlyRetransSegs,LostSegs,RepeatSegs,FECParityShards,FECErrs,FECRecovered,FECShortShards
            # 2020-10-31_08:38:12,86986264,0,0,0,0,0,0,0,0,0,0,0,0,0,119100802,0,0,0,0,0,0,0,0,0
            # 0
            # 逐行读取
            result = []
            for line in open(band_width_95_file_path):
                if 'unix' in line.strip().lower():
                    continue
                lr = line.strip().split(',')
                result.append([lr[0], lr[1], lr[15]])
            return result
        else:
            return []
    except:
        return []


def get_my_snmp_log():
    bandwidthlogpath="/usr/monclient/logs/snmp.log"
    try:
        if os.path.isfile(bandwidthlogpath):
            result = []
            for line in open(bandwidthlogpath):
                result.append(line.strip().split(','))
            return result
        else:
            return []
    except:
        return []


if __name__=="__main__":
    with open('/opt/soft/dcache/deviceid',) as f:
        deviceid = f.read().strip()

    wf_path="/root/{}.json".format(deviceid)
    with open(wf_path, 'w') as f:
        json.dump(dict(aqysnmp=get_aqy_snmp_log(), mysnmp=get_my_snmp_log()), f)
    # 保存到 淮安pve 01 虚拟机
    password="Asdfghjkl123@"
    child = pexpect.spawn("scp -P 201 {cwd} hadxha01.vszone.com:/root/snmplogs ".format(cwd=wf_path))
    flag = child.expect(["yes/no", "password", pexpect.EOF, pexpect.TIMEOUT])
    print(flag)
    if flag == 0:  # 0匹配成功，1匹配失败，2超时，3子程序退出
        print("1.开始上传" )
        try:
            child.sendline("yes")
            child.expect("password")
            child.sendline(password)  # send不换行，sendline换行
            child.expect('added')  # 远程命令返回成功，无此行，会显示已上传，但是实际没传输过去。
            print("1.已上传")
        except Exception as e:
            print("1.上传失败")
            print(e)
        finally:
            child.close()
    elif flag == 1:
        print("2.开始上传")
        try:
            child.sendline(password)
            child.expect('added')
            print("2.已上传")
        except Exception as e:
            print("2.上传失败")
            print(e)
        finally:
            child.close()
    else:
        print("3.未上传")
        child.close()
    os.system("rm -rf {}".format(wf_path))
    os.system("rm -rf /root/getsnmp.py")